package com.syj.jsxjj.ui.lend.fragment;


import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.syj.jsxjj.R;
import com.syj.jsxjj.app.App;
import com.syj.jsxjj.base.BaseFragment;
import com.syj.jsxjj.config.Constant;
import com.syj.jsxjj.http.HttpManager;
import com.syj.jsxjj.http.HttpSubscriber;
import com.syj.jsxjj.ui.lend.adapter.LoanListAdapter;
import com.syj.jsxjj.ui.lend.bean.LoanList;
import com.syj.jsxjj.ui.lend.bean.ProductDetailBean;
import com.syj.jsxjj.ui.main.WebViewActivity;
import com.syj.jsxjj.util.Cn2Spell;
import com.syj.jsxjj.util.ToastUtil;
import com.syj.jsxjj.util.Tool;
import com.syj.jsxjj.widget.recycler.BaseRecyclerAdapter;
import com.syj.jsxjj.widget.recycler.DividerItemDecoration;
import com.syj.jsxjj.widget.refresh.base.OnLoadMoreListener;
import com.syj.jsxjj.widget.refresh.base.OnRefreshListener;
import com.syj.jsxjj.widget.refresh.base.SwipeToLoadLayout;
import com.umeng.analytics.MobclickAgent;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * 借款产品列表
 */
public class LoanListFragment extends BaseFragment implements OnRefreshListener, OnLoadMoreListener {
    public String indexMoneyType, productType, borrowMonery, borrowLimit, accumulation,
            creditCard, shoppingAccount, professional, address, source, sort;
    public String checkMoney, proType;// 筛选金额,筛选类型
    public String _LoanApply_sy_wydkP;//
    @BindView(R.id.swipe_target)
    RecyclerView mSwipeTarget;
    @BindView(R.id.refresh)
    SwipeToLoadLayout mRefresh;
    private LoanListAdapter mAdapter;
    private int numPerPage = 15, pageNum = 1;
    private boolean isPull = true;
    private LoanList mResult;
    private View footView;
    private DividerItemDecoration itemDecoration;
    private TextView tvRecommend;

    public static LoanListFragment getInstance(Bundle bundle) {
        LoanListFragment fragment = new LoanListFragment();
        if (bundle != null) {
            fragment.setArguments(bundle);
        }
        return fragment;
    }

    @Override
    public int getLayoutId() {
        return R.layout.pull_recycle;
    }

    @Override
    public void initPresenter() {

    }

    @Override
    public void loadData() {
        if (getArguments() != null) {
            checkMoney = getArguments().getString("checkMoney");  //贷款 金额
            indexMoneyType = getArguments().getString("indexMoneyType"); // one two three four
            productType = getArguments().getString("productType");  //贷款类型
            borrowMonery = getArguments().getString("borrowMonery");
            borrowLimit = getArguments().getString("borrowLimit");
            accumulation = getArguments().getString("accumulation");
            creditCard = getArguments().getString("creditCard");
            shoppingAccount = getArguments().getString("shoppingAccount");
            professional = getArguments().getString("professional");
            address = getArguments().getString("address");
            source = getArguments().getString("source");

            sort = getArguments().getString("sort"); //排序字段：1 利率 2 额度
        }

        mRefresh.setOnRefreshListener(this);
        mRefresh.setOnLoadMoreListener(this);
        mSwipeTarget.setLayoutManager(new LinearLayoutManager(mContext));
        //mSwipeTarget.addItemDecoration(new MyItemDecoration(mContext,MyItemDecoration.HORIZONTAL_LIST));
        mAdapter = new LoanListAdapter();
        mSwipeTarget.setAdapter(mAdapter);
        //产品列表点击事件
        mAdapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClick() {
            @Override
            public void onItemClick(View view, int position) {
                if (Tool.isFastDoubleClick()) return;

                toSubscribe(HttpManager.getApi().productInfoDetails(mAdapter.getData().get(position).getEid()), new HttpSubscriber<ProductDetailBean>() {
                    @Override
                    protected void _onStart() {
                        App.loadingDefault(mActivity);
                    }

                    @Override
                    protected void _onNext(ProductDetailBean productDetailBean) {
                        Intent intent = new Intent(mActivity, WebViewActivity.class);
                        intent.putExtra("url",productDetailBean.getProductInfo().getJunkLink());
                        startActivity(intent);
                    }

                    @Override
                    protected void _onError(String message) {
                        ToastUtil.showToast(message);
                    }

                    @Override
                    protected void _onCompleted() {
                        App.hideLoading();
                    }
                });
            }
        });
//        loadListData();
        refreshFirst();
        autoLoading(mRefresh, mSwipeTarget);
    }

    public TextView getTvRecommend() {
        return tvRecommend;
    }

    public void setTvRecommend(TextView tvRecommend) {
        this.tvRecommend = tvRecommend;
    }


    public void refreshFirst() {
        mRefresh.post(new Runnable() {
            @Override
            public void run() {
                mRefresh.setRefreshing(true);
            }
        });
    }

    public void loadListData() {
        final Map<String, String> map = new HashMap<>();
        if (!TextUtils.isEmpty(productType)) {
            map.put("productType", productType);
        }
        if (!TextUtils.isEmpty(borrowMonery)) {
            map.put("borrowMonery", borrowMonery);
        }
        if (!TextUtils.isEmpty(borrowLimit)) {
            map.put("borrowLimit", borrowLimit);
        }
        if (!TextUtils.isEmpty(accumulation)) {
            map.put("accumulation", accumulation);
        }
        if (!TextUtils.isEmpty(creditCard)) {
            map.put("creditCard", creditCard);
        }
        if (!TextUtils.isEmpty(shoppingAccount)) {
            map.put("shoppingAccount", shoppingAccount);
        }
        if (!TextUtils.isEmpty(professional)) {
            map.put("professional", professional);
        }
        if (!TextUtils.isEmpty(address)) {
            map.put("address", address);
        }
        if (!TextUtils.isEmpty(indexMoneyType)) {
            map.put("indexMoneyType", indexMoneyType);
        }
        if (!TextUtils.isEmpty(source)) {
            map.put("source", source);
        }
        if (!TextUtils.isEmpty(sort)) {
            map.put("sort", sort);
        }
        if (!TextUtils.isEmpty(checkMoney)) {
            if ("金额不限".equals(checkMoney)) {
                map.put("checkMoney", "");
            } else if ("2000以下".equals(checkMoney)) {
                map.put("checkMoney", "1");
            } else if ("2000-5000".equals(checkMoney)) {
                map.put("checkMoney", "2");
            } else if ("5000-10000".equals(checkMoney)) {
                map.put("checkMoney", "3");
            } else if ("10000-20000".equals(checkMoney)) {
                map.put("checkMoney", "4");
            } else if ("20000-50000".equals(checkMoney)) {
                map.put("checkMoney", "5");
            } else {
                map.put("checkMoney", "6");
            }

        }
        map.put("appType", "1");
        map.put("numPerPage", numPerPage + "");
        map.put("pageNum", pageNum + "");

        toSubscribe(HttpManager.getApi().findProductInfoList(map), new HttpSubscriber<LoanList>() {
            @Override
            protected void _onStart() {

            }

            @Override
            protected void _onNext(LoanList result) {
                onComplete(mRefresh);
                if (result == null) {
                    mAdapter.clearData();
                    if (mAdapter.getFootersCount() == 0) {
                        View view = LayoutInflater.from(mContext).inflate(R.layout.layout_no_data, null);
                        view.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
                        mAdapter.addFooterView(view);
                    }
                    if (tvRecommend != null) {
                        tvRecommend.setVisibility(View.GONE);
                    }
                } else {
                    mResult = result;
                    if (isPull) {
                        mAdapter.clearData();
                        mRefresh.setLoadMoreEnabled(true);
                        if (result.getList() == null || result.getList().size() == 0) {
                            if (mAdapter.getFootersCount() == 0) {
                                View view = LayoutInflater.from(mContext).inflate(R.layout.layout_no_data, null);
                                view.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
                                mAdapter.addFooterView(view);
                            }
                        } else {
                            if (mAdapter.getFootersCount() > 0)
                                mAdapter.clearFooterView();
                        }
                    }

                    mAdapter.setLabelMap(result.getLabelMap());
                    mAdapter.setLabelColMap(result.getLabelColMap());

                    mAdapter.addData(result.getList());
                    if (tvRecommend != null) {
                        if (TextUtils.isEmpty(result.getShortDesc())) {
                            tvRecommend.setVisibility(View.GONE);
                        } else {
                            tvRecommend.setText(result.getShortDesc());
                            tvRecommend.setVisibility(View.VISIBLE);
                        }
                    }

                    //底线
                    if (mResult.getPageInfo() != null) {
                        if (mResult.getPageInfo().getTotalPage() <= pageNum) {
                            mRefresh.setLoadingMore(false);
                            mRefresh.setLoadMoreEnabled(false);

                            mSwipeTarget.post(new Runnable() {
                                @Override
                                public void run() {
                                    RecyclerView.LayoutManager manager = mSwipeTarget.getLayoutManager();
                                    int rvHeight = mSwipeTarget.getMeasuredHeight();
                                    int itemHeight = 0;
                                    if (manager.getChildCount() > 0) {
                                        for (int i = 0; i < manager.getChildCount(); i++) {
                                            itemHeight += mSwipeTarget.getChildAt(i).getMeasuredHeight();
                                            itemHeight += ((ViewGroup.MarginLayoutParams) mSwipeTarget.getChildAt(i).getLayoutParams()).topMargin;
                                        }
                                    }

                                    if (mAdapter.getFootersCount() == 0) {
                                        View view = LayoutInflater.from(mContext).inflate(R.layout.encrypt_footer_item, null);
                                        if (rvHeight - itemHeight > 120) {
                                            view.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, rvHeight - itemHeight));
                                        } else {
                                            view.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 120));
                                        }
                                        mAdapter.addFooterView(view);
                                    }
                                }
                            });
                        }
                    }
                }
            }

            @Override
            protected void _onError(String message) {
                onComplete(mRefresh);
                ToastUtil.showToast(message);
            }

            @Override
            protected void _onCompleted() {

            }
        });
    }

    @Override
    public void onLoadMore() {
        if (mResult != null && mResult.getPageInfo() != null) {
            if (mResult.getPageInfo().getTotalPage() > pageNum) {
                pageNum++;
                isPull = false;
                loadListData();
//                if (footView == null) {
//                    footView = LayoutInflater.from(mContext).inflate(R.layout.encrypt_footer_item, null);
//                    mAdapter.addFooterView(footView, Tool.dip2px(mContext,120));
//                    itemDecoration.setFootViewCount(mAdapter.getFootersCount());
//                    mSwipeTarget.addItemDecoration(itemDecoration);
//                }
            } else {
//                ToastUtil.showToast("已无更多数据");
                mRefresh.setLoadingMore(false);
                mRefresh.setLoadMoreEnabled(false);

                //底线
                if (mAdapter.getFootersCount() == 0) {
                    View view = LayoutInflater.from(mContext).inflate(R.layout.encrypt_footer_item, null);
                    view.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 120));
                    mAdapter.addFooterView(view);
                }
            }
        } else {
            mRefresh.setLoadingMore(false);
        }
    }

    @Override
    public void onRefresh() {
        pageNum = 1;
        isPull = true;
        loadListData();
    }

}
